package com.erf.message;

import com.erf.tools.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
@Slf4j
public class SubmitRequestResponse extends BaseMessage {
    private int code;
    private int resultLength;
    private Object result;


    @Override
    public void encode(ByteBuf byteBuf) {
        byte[] bytes = ByteUtil.encodeObjectToBytes(result);
        resultLength = bytes.length;

        byteBuf.writeInt(12 + 4 + 4 + resultLength);
        byteBuf.writeInt(0x80000002);
        byteBuf.writeInt(this.getSequence());

        byteBuf.writeInt(code);
        byteBuf.writeInt(resultLength);
        byteBuf.writeBytes(bytes);
    }

    @Override
    public BaseMessage decode(int length, int command, int sequence, ByteBuf body) {
        this.setLength(length);
        this.setCommand(command);
        this.setSequence(sequence);
        code = body.readInt();
        resultLength = body.readInt();
        byte[] bytes = new byte[resultLength];
        body.readBytes(bytes);
        result = ByteUtil.decodeBytesToObject(bytes);
        return this;
    }
}
